package com.toymate.ai.llm.model.coze;

import com.toymate.modules.iot.entity.IotRole;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;

/**
 * CozeSSEEventSourceListener
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
public class CozeSSEEventSourceListener extends EventSourceListener {

    private static final Pattern SENTENCE_END_PATTERN = Pattern.compile("[。！？；?.!;]");

    private StringBuilder answer = new StringBuilder();

    private StringBuilder totalAnswer = new StringBuilder();

    private int count;

    private AtomicInteger index = new AtomicInteger(0);
    private String productId;

    private String deviceNum;

    private String conversationId;

    private String question;


    private IotRole role;


    public CozeSSEEventSourceListener(String productId, String deviceNum, String question, IotRole role) {
        this.productId = productId;
        this.deviceNum = deviceNum;
        this.question = question;
        this.role = role;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onOpen(EventSource eventSource, Response response) {
        log.info("======== 对话开始 ========");
    }

    /**
     * {@inheritDoc}
     */
    @SneakyThrows
    @Override
    public void onEvent(EventSource eventSource, String id, String type, String data) {

    }

    @Override
    public void onClosed(EventSource eventSource) {
    }

    @SneakyThrows
    @Override
    public void onFailure(EventSource eventSource, Throwable t, Response response) {
        if (Objects.isNull(response)) {
            return;
        }
        ResponseBody body = response.body();
        if (Objects.nonNull(body)) {
            log.error("Coze  sse连接异常data：{}，异常：{}", body.string(), t);
        } else {
            log.error("Coze  sse连接异常data：{}，异常：{}", response, t);
        }
        eventSource.cancel();
    }

}
